import {defineStore} from 'pinia'
import {ref} from 'vue'
import {login, loginByPassword, sendVerifyCode, userLogout} from '@/api/user'

export const useUserStore = defineStore('user', () => {
    const token = ref(localStorage.getItem('token') || '')
    const userInfo = ref(JSON.parse(localStorage.getItem('userInfo')) || null)

    // 手机验证码登录
    const loginWithCode = async (phone, code) => {
        try {
            const res = await login(phone, code)
            const {token: userToken, user} = res

            localStorage.setItem('token', userToken)
            localStorage.setItem('userInfo', JSON.stringify(user))
            token.value = userToken
            userInfo.value = user

            return res
        } catch (error) {
            throw error
        }
    }

    // 账号密码登录
    const loginWithPassword = async (params) => {
        try {
            const res = await loginByPassword(params)
            setUserInfo(res)
            return res
        } catch (error) {
            throw error
        }
    }

    // 发送验证码
    const sendCode = async (phone) => {
        try {
            return await sendVerifyCode(phone)
        } catch (error) {
            throw error
        }
    }

    // 本地赋值
    const setUserInfo = (data) => {
        if (data.token){
            token.value = data.token
            localStorage.setItem('token', data.token)
        }
        userInfo.value = data.user
        localStorage.setItem('userInfo', JSON.stringify(data.user))
    }
    const logout = async () => {
        try {
            await userLogout()
        } catch (e) {
            console.log(e)
        } finally {
            token.value = ''
            userInfo.value = null
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
        }

    }

    return {
        token,
        userInfo,
        loginWithCode,
        loginWithPassword,
        setUserInfo,
        sendCode,
        logout
    }
})
